const ImageSource = require("../../utils/image_path.js");
const { request }  = require('../../request/index.js');
const crypto = require("../../utils/test");
const dataGet=require("../../request/dataGet.js")
const app=getApp();
Page({
    data: {
        cardData:{}
    },
    onLoad() {
        wx.showLoading({
            title:"加载中",
            duration:6000,
        })
        // if(!app.globalData.openId){
        //     this.getOpenId()
        // }
        // var p=this.getAnimationOnload()
        // console.log(p);
        // p.then(()=>{
        //     wx.switchTab({
        //         url:'../cardGet/index'
        //     })
        // })
        setTimeout(()=>{
            this.getData()
        },200)
    },
    async getData(){
        //获取openID
        await dataGet.getOpenId();
        //获取动画资源
        await this.getAnimationOnload()
        //获取用户数字藏品数据
        await dataGet.getUserCardData();
        //获取用户个人信息数据
        await dataGet.getUserData()
        //获取用户订单数据
        await dataGet.getOrders()
        //获取用户优惠券数据
        await dataGet.getCouples()
        wx.switchTab({
            url:'../cardGet/index'
        })
    },
    //获取openId
    getOpenId(){
        return new Promise(resolve => {
            let params ={
                url: '/getOpenId',
                method:'GET',
                header: {
                    'content-type': 'application/json'
                },
            }
            request(params).then((res)=>{
                let data=crypto.AES_DE(res.data);
                app.globalData.openId=data
                resolve()
            })
        })
    },
    //获取动画卡片
    getAnimationOnload(){
        return new Promise((resolve)=>{
            var fileList=new Array();
            for(var i=0;i<ImageSource.imageList[0].length;i++){
                var str=ImageSource.Base+ImageSource.page[0]+ImageSource.imageList[0][i]
                fileList.push(str)
            }
            var that=this;
            wx.cloud.getTempFileURL({
                fileList:fileList,
                success:res=>{
                    var imgSrcList=new Array();
                    const urls = res.fileList
                    console.log('-------'+res.fileList[0].tempFileURL);
                    that.setData({
                        imgFileList:res.fileList
                    })
                    const requests = urls.map(url => {
                        return new Promise(resolve => {
                            wx.downloadFile({
                                url: url.tempFileURL,
                                success (r) {
                                    // console.log(url.tempFileURL.substring( url.tempFileURL.length-3));
                                    if(url.tempFileURL.substring( url.tempFileURL.length-3)=="png")
                                        resolve(r.tempFilePath);
                                    else{
                                        resolve(url.tempFileURL);

                                    }
                                },
                                fail:err=>{
                                    console.log(err)
                                }
                            })
                        })
                    })
                    var imgSrcList=new Array()
                    Promise.all(requests)
                        .then(objectUrls => {
                            imgSrcList.push(objectUrls)
                            console.log(imgSrcList);
                            wx.setStorageSync("CardGetAnimation",{time:Date.now(),data:imgSrcList})
                        });
                    resolve()
                },
            })
        })
    },
    //获取用户卡片
    getUserCardData(){
        return new Promise((resolve)=>{
            var that=this;
            let params={
                url:'/userCard',
                method: 'GET',
                data: {
                    openId:app.globalData.openId,
                },
            }
            request(params).then(res=>{
                const data=JSON.parse(crypto.AES_DE(res.data))
                //返回时间排序的打乱的卡片图
                let category = []
                let categoryAll=["生椰拿铁","经典美式","经典拿铁","樱花拿铁","抹茶拿铁","摩卡"]
                var temp=Object.values(data)
                var fileList=new Array();
                //获取全部的图片链接
                for (let i = 0; i < Object.keys(data).length; i++){
                    for(let j=0;j<temp[i].length;j++){
                        fileList.push(ImageSource.Base+"/icon/roleCard/"+temp[i][j].imageSrc);
                    }
                }
                fileList.push(ImageSource.Base+"/icon/roleCard/unknownCard.png");
                fileList.push(ImageSource.Base+"/icon/roleCard/blank.png");
                new Promise(resolve =>{
                    wx.cloud.getTempFileURL({
                        fileList:fileList,
                        success:res=>{
                            var values=[];
                            var otherData=[];
                            var count=0;
                            //链接重新赋值
                            for (let i = 0; i < Object.keys(data).length; i++){
                                for(let j=0;j<temp[i].length;j++){
                                    temp[i][j].imageSrc=res.fileList[count++].tempFileURL;
                                }
                            }
                            otherData.push(res.fileList[count++].tempFileURL)
                            otherData.push(res.fileList[count++].tempFileURL)
                            for (let i = 0; i < Object.keys(data).length; i++){
                                category.push(Object.keys(data)[i]);
                            }
                            //按照全部重新赋值
                            categoryAll.forEach(tmp=>{
                                let index=category.indexOf(tmp);
                                if(index==-1){
                                    values.push([])
                                }
                                else{
                                    values.push(temp[index]);
                                }
                            })
                            resolve([values,otherData]);
                        }
                    })
                }).then((values)=>{
                    console.log(values)
                    wx.setStorageSync("userCards",{time:Date.now(),data:values[0]});
                    wx.setStorageSync("nullCardData",{time:Date.now(),data:values[1]});
                    resolve();
                })
            })
        })
    },

    //获取环境资源
    getUserData(){
        return new Promise(resolve => {
            let params={
                url:'/user',
                method: 'GET',
                data: {
                    openId:app.globalData.openId,
                },
            }
            request(params).then(res=>{
                console.log(res)
                const data=JSON.parse(crypto.AES_DE(res.data))
                var src=ImageSource.Base+ImageSource.page[7]+data.image
                new Promise((resolve) =>{
                    wx.cloud.getTempFileURL({
                        fileList:[src],
                        success:r=>{
                            data.image=r.fileList[0].tempFileURL;
                            resolve(data)
                        },
                    })
                }).then(trees=>{
                    console.log(trees)
                    wx.setStorageSync("userData",{time:Date.now(),data:trees})
                    resolve()
                })
            })
        })
    },
    //获取订单
    getOrders(){
        return new Promise((resolve=>{
            let params={
                url:'/getOrders',
                method: 'GET',
                data: {
                    openId:app.globalData.openId
                },
            }
            request(params).then(res=>{
                const data=JSON.parse(crypto.AES_DE(res.data));
                wx.setStorageSync("userOrders",{time:Date.now(),data:data});
                resolve()
            })

        }))
    },
    //获取优惠券
    getCouples(){
        return new Promise((resolve=>{
            let params={
                url:'/getCouples',
                method: 'GET',
                data: {
                    openId:app.globalData.openId
                },
            }
            request(params).then(res=>{
                console.log("更新优惠券")
                const data=JSON.parse(crypto.AES_DE(res.data));
                console.log(data);
                wx.setStorageSync("userCouples",{time:Date.now(),data:data});
                resolve()
            })

        }))
    },

})